﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management; 

namespace MSysMonNET
{
    public class MSysCheckServerLoad
    {
        /// <summary>
        /// This method uses WMI to check for the current number users connected to
        /// the IIS on a target machine
        /// </summary>
        /// <param name="scope">the remote server's management scope</param>
        /// <returns>an unsigned integer with the current number of users connected 
        /// to the Web Server</returns>
        public uint checkWebUsers(ManagementScope scope)
        {

            uint result = 0;

            try
            {
                //Query system for Operating System information
                ObjectQuery query = new ObjectQuery(
                    "select CurrentConnections from Win32_PerfFormattedData_W3SVC_WebService where Name=\"_Total\"");
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(scope, query);
                searcher.Options.Rewindable = false;
                searcher.Options.ReturnImmediately = true;

                ManagementObjectCollection queryCollection = searcher.Get();

                foreach (ManagementObject objWeb in queryCollection)
                {
                    result = (uint)objWeb["CurrentConnections"];
                }
            }
            catch 
            {
                return 0;
            }

            return result;

        }
        /// <summary>
        /// This method checks for the activity on a target server's procesor
        /// </summary>
        /// <param name="scope">the remote server's management scope</param>
        /// <returns>an unsigned long with the percentage of activity on the CPU(s)</returns>
        public ulong checkCPUload(ManagementScope scope)
        {

            ulong result = 0;

            try
            {
                //Query system for Operating System information
                ObjectQuery query = new ObjectQuery(
                    "select PercentProcessorTime from Win32_PerfFormattedData_PerfOS_Processor where Name=\"_Total\"");
                ManagementObjectSearcher searcher =
                    new ManagementObjectSearcher(scope, query);
                searcher.Options.Rewindable = false;
                searcher.Options.ReturnImmediately = true;

                ManagementObjectCollection queryCollection = searcher.Get();

                foreach (ManagementObject objWeb in queryCollection)
                {
                    result = (ulong)objWeb["PercentProcessorTime"];
                }
            }
            catch 
            {
                return 100;
            }

            return result;

        }
    }
}
